package com.enjoychain.www.security.service.impl;

import com.enjoychain.www.common.constrants.TaskStatus;
import com.enjoychain.www.security.entity.*;
import com.enjoychain.www.security.entity.job.JobDetailItem;
import com.enjoychain.www.security.entity.job.JobInfo;
import com.enjoychain.www.security.entity.task.TaskDetailItem;
import com.enjoychain.www.security.entity.task.TaskInfo;
import com.enjoychain.www.security.mapper.JobInfoMapper;
import com.enjoychain.www.security.pojo.TableMeta;
import com.enjoychain.www.security.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 作业基础表 服务实现类
 * </p>
 *
 * @author ddmonk
 * @since 2023-01-29
 */
@Service
public class JobInfoServiceImpl extends ServiceImpl<JobInfoMapper, JobInfo> implements IJobInfoService {

    @Autowired
    IJobDetailItemService itemService;

    @Autowired
    ICorpBasicInfoService basicInfoService;


    @Autowired
    IXcBasicService basicService;


    @Autowired
    ITaskInfoService taskInfoService;

    @Autowired
    ITaskDetailItemService taskDetailItemService;


    @Autowired
    ICorpEpEquipInfoService epEquipInfoService;

    @Autowired
    ICorpEpBasicService epBasicService;

    @Autowired
    ICorpEpMergencyPlanService mergencyPlanService;

    @Autowired
    ICorpEpGasEquipmentService gasEquipmentService;

    @Autowired
    ICorpEpNoiseProtectService noiseProtectService;

    @Autowired
    ICorpEpHwService hwService;


    private static int sort;

    @Override
    public JobInfo getJobDetail(String id) {
        JobInfo info = this.getById(id);
        info.setItems(itemService.getJobItems(id));
        return info;
    }

    @Override
    @Transactional
    public boolean start(String id) {
        JobInfo info = getJobDetail(id);
        List<CorpBasicInfo> basicInfos = getHandlerCompany();
        for (CorpBasicInfo corpBasicInfo : basicInfos){
            buildSingleTask(corpBasicInfo,info);
        }
        //todo 获取需要构建任务的企业信息。
        return true;
    }


    List<CorpBasicInfo> getHandlerCompany(){
        return basicInfoService.list();
    }



    @Override
    public boolean buildSingleTask(CorpBasicInfo corp, JobInfo info){
        sort = 0;
        String taskId = UUID.randomUUID().toString().replace("-","");
        TaskInfo taskInfo = new TaskInfo();
        taskInfo.setTaskNo(basicService.getTaskNo());
        taskInfo.setId(taskId);
        taskInfo.setCorpId(corp.getId());
        taskInfo.setCorpName(corp.getName());
        taskInfo.setStatus(TaskStatus.PLAN);
        taskInfo.setType(info.getType());
        taskInfo.setName(corp.getName() + "_" + info.getName());
        taskInfoService.save(taskInfo);
        for (JobDetailItem jobDetailItem : info.getItems()){
            if (StringUtils.isNotEmpty(jobDetailItem.getBasicInfo())){
                // 1、先获取有
                if (jobDetailItem.getBasicInfo().contains("{")){
                    //1 、获取参数
                    List<String> params = new ArrayList<>();
                    String content = jobDetailItem.getBasicInfo();
                    while(content.contains("}")){
                        int beginIndex = content.indexOf("{");
                        int endIndex = content.indexOf("}");
                        params.add(content.substring(beginIndex+1,endIndex));
                        content = content.substring(endIndex+1);
                    }
                    //2、 获取对应的表与字段
                    TableMeta meta = buildTableMeta(params);
                    //3、 执行sql获取值
                    buildTaskDetailItemWithDB(jobDetailItem,taskId,meta,corp.getId());
                }else {
                    //有核算数据，但是没有需要从表中获取的值。
                    TaskDetailItem item = convertJobItemToTaskItem(jobDetailItem, taskId, jobDetailItem.getBasicInfo());
                    taskDetailItemService.save(item);
                }
            }else{
                TaskDetailItem item = convertJobItemToTaskItem(jobDetailItem, taskId, jobDetailItem.getBasicInfo());
                taskDetailItemService.save(item);
            }
        }
        return true;
    }

    private void buildTaskDetailItemWithDB(JobDetailItem jobDetailItem, String taskId, TableMeta meta, String corpId) {
        switch (meta.getTableName()){
            case "corp_ep_equip_info" : buildEquipInfoItems(jobDetailItem,taskId,meta,corpId);break;
            case "corp_ep_basic" : buildBasic(jobDetailItem,taskId,meta,corpId);break;
            case "corp_ep_mergency_plan": buildMergencyPlay(jobDetailItem,taskId,meta,corpId);break;
            case "corp_ep_gas_equipment": buildGasEquipment(jobDetailItem,taskId,meta,corpId);break;
            case "corp_ep_noise_protect" : buildNoiseProtect(jobDetailItem,taskId,meta,corpId);break;
            case "corp_ep_hw": buildHw(jobDetailItem,taskId,meta,corpId);break;
            default: break;
        }
    }

    private void buildHw(JobDetailItem jobDetailItem, String taskId, TableMeta meta, String corpId) {
        List<CorpEpHw> corpEpHws = hwService.listWithStatus(0,corpId);
        for (CorpEpHw info : corpEpHws){
            String basicInfo = jobDetailItem.getBasicInfo();
            if (basicInfo.contains("{corp_ep_hw:contract_desc}")){
                basicInfo = basicInfo.replace("{corp_ep_hw:contract_desc}",info.getContractDesc());
            }
            if (basicInfo.contains("{corp_ep_hw:hw_name}")){
                basicInfo = basicInfo.replace("{corp_ep_hw:hw_name}",info.getHwName());
            }
            TaskDetailItem item = convertJobItemToTaskItem(jobDetailItem, taskId,basicInfo);
            taskDetailItemService.save(item);
        }
    }

    private void buildNoiseProtect(JobDetailItem jobDetailItem, String taskId, TableMeta meta, String corpId) {
        List<CorpEpNoiseProtect> corpEpNoiseProtects = noiseProtectService.listWithStatus(0, corpId);
        for (CorpEpNoiseProtect info : corpEpNoiseProtects){
            String basicInfo = jobDetailItem.getBasicInfo();
            if (basicInfo.contains("{corp_ep_noise_protect:noise_protect}")){
                basicInfo = basicInfo.replace("{corp_ep_noise_protect:noise_protect}",info.getNoiseProtect());
            }
            TaskDetailItem item = convertJobItemToTaskItem(jobDetailItem, taskId,basicInfo);
            taskDetailItemService.save(item);
        }
    }

    private void buildGasEquipment(JobDetailItem jobDetailItem, String taskId, TableMeta meta, String corpId) {
        //1. 工段排序
        if (jobDetailItem.getBasicInfo().contains("{corp_ep_gas_equipment:product_section}")){
            List<CorpEpGasEquipment> sections = gasEquipmentService.listSection(0, corpId);
            for (CorpEpGasEquipment info : sections) {
                String basicInfo = jobDetailItem.getBasicInfo();
                basicInfo = basicInfo.replace("{corp_ep_gas_equipment:product_section}", info.getProductSection());
                TaskDetailItem item = convertJobItemToTaskItem(jobDetailItem, taskId,basicInfo);
                taskDetailItemService.save(item);
            }
        }else {
            List<CorpEpGasEquipment> corpEpGasEquipments = gasEquipmentService.listWithStatus("0", corpId);
            for (CorpEpGasEquipment info : corpEpGasEquipments) {
                String basicInfo = jobDetailItem.getBasicInfo();
                if (basicInfo.contains("{corp_ep_gas_equipment:exhaust_funnel_no}") && basicInfo.contains("{corp_ep_gas_equipment:pollution_factor}")) {
                    basicInfo = basicInfo.replace("{corp_ep_gas_equipment:exhaust_funnel_no}", info.getExhaustFunnelNo());
                    basicInfo = basicInfo.replace("{corp_ep_gas_equipment:pollution_factor}", info.getPollutionFactor());
                }
                TaskDetailItem item = convertJobItemToTaskItem(jobDetailItem, taskId, basicInfo, sort);
                taskDetailItemService.save(item);
            }
        }
    }

    private void buildMergencyPlay(JobDetailItem jobDetailItem, String taskId, TableMeta meta, String corpId) {
        List<CorpEpMergencyPlan> corpEpMergencyPlans = mergencyPlanService.listWithStatus(0, corpId);
        for (CorpEpMergencyPlan info : corpEpMergencyPlans){
            String basicInfo = jobDetailItem.getBasicInfo();
            if (basicInfo.contains("{corp_ep_mergency_plan:plan_name}")){
                basicInfo = basicInfo.replace("{corp_ep_mergency_plan:plan_name}",info.getPlanName());
            }
            if (basicInfo.contains("{corp_ep_mergency_plan:lagoon_desc}")){
                basicInfo = basicInfo.replace("{corp_ep_mergency_plan:lagoon_desc}",info.getLagoonDesc());
            }
            TaskDetailItem item = convertJobItemToTaskItem(jobDetailItem, taskId,basicInfo);
            taskDetailItemService.save(item);
        }
    }

    private void buildBasic(JobDetailItem jobDetailItem, String taskId, TableMeta meta, String corpId) {
        List<CorpEpBasic> corpEpBasics = epBasicService.listByCorpId(corpId);
        for (CorpEpBasic info : corpEpBasics){
            String basicInfo = jobDetailItem.getBasicInfo();
            basicInfo = basicInfo.replace("{corp_ep_basic:corp_craft}",info.getCorpCraft());
            TaskDetailItem item = convertJobItemToTaskItem(jobDetailItem, taskId,basicInfo);
            taskDetailItemService.save(item);
        }
    }


    private void buildEquipInfoItems(JobDetailItem jobDetailItem,String taskId, TableMeta meta, String corpId) {
        //获取状态正常的数据
        List<CorpEpEquipInfo> corpEpEquipInfos = epEquipInfoService.listWithStatus("0",corpId);
        for (CorpEpEquipInfo info : corpEpEquipInfos){
            String basicInfo = jobDetailItem.getBasicInfo();
            basicInfo = basicInfo.replace("{corp_ep_equip_info:equip_name}",info.getEquipName());
            basicInfo = basicInfo.replace("{corp_ep_equip_info:num}",info.getEquipNum().toString());
            TaskDetailItem item = convertJobItemToTaskItem(jobDetailItem, taskId, basicInfo);
            taskDetailItemService.save(item);
        }
    }

    private TableMeta buildTableMeta(List<String> params) {
        TableMeta meta = new TableMeta();
        for (String param : params){
            String[] list = param.split(":");
            meta.setTableName(list[0]);
            meta.setField(list[1]);
        }
        return meta;
    }

    private TaskDetailItem convertJobItemToTaskItem(JobDetailItem jobDetailItem, String taskId, String basicInfo) {
        TaskDetailItem item =  TaskDetailItem.builder()
                .taskId(taskId)
                .itemLevel(jobDetailItem.getItemLevel())
                .content(jobDetailItem.getContent())
                .basicInfo(basicInfo)
                .itemSort(sort)
                .keyId(jobDetailItem.getKeyId())
                .keyName(jobDetailItem.getKeyName())
                .targetName(jobDetailItem.getTargetName())
                .targetId(jobDetailItem.getTargetId())
                .needImage(jobDetailItem.getNeedImage())
                .remark(jobDetailItem.getRemark())
                .type(jobDetailItem.getType())
                .typeDesc(jobDetailItem.getTypeDesc())
                .element(jobDetailItem.getElement())
                .build();
        sort ++;
        return item;
    }

    private TaskDetailItem convertJobItemToTaskItem(JobDetailItem jobDetailItem, String taskId, String basicInfo, int sort) {
        TaskDetailItem item =  TaskDetailItem.builder()
                .taskId(taskId)
                .itemLevel(jobDetailItem.getItemLevel())
                .content(jobDetailItem.getContent())
                .basicInfo(basicInfo)
                .itemSort(sort)
                .keyId(jobDetailItem.getKeyId())
                .keyName(jobDetailItem.getKeyName())
                .targetName(jobDetailItem.getTargetName())
                .targetId(jobDetailItem.getTargetId())
                .needImage(jobDetailItem.getNeedImage())
                .remark(jobDetailItem.getRemark())
                .type(jobDetailItem.getType())
                .typeDesc(jobDetailItem.getTypeDesc())
                .element(jobDetailItem.getElement())
                .build();
        return item;
    }

}
